import { omitFields } from '@/common/global'
import {
  addMenuApi,
  updateMenuApi,
  getMenuPaginationApi,
  deleteMenuApi
} from '@/services'
import { omit } from 'lodash'
import { Button, Card, Form, Icon, InputText, Message, Modal, Page, Table, Radio, getValueIfQualified, Typography } from 'magic-ui-react'
import { ModalHandle } from 'magic-ui-react/dist/Modal/interface'
import { ActionType, ColumnType, TableBaseType } from 'magic-ui-react/dist/Table/interface'
import { useRef, useState } from 'react'
import styles from './styles.module.less'
import { TableDataType } from './types'

const MenusList = () => {

  const modalRef = useRef<ModalHandle>()
  const actionRef = useRef<ActionType>()

  const [form] = Form.useForm()

  const [pagination, setPagination] = useState({
    total: 0
  })
  const [title, setTitle] = useState('')
  const [radioValue, setRadioValue] = useState('one')

  const columns: ColumnType<TableDataType>[] = [
    {
      title: '标题',
      dataKey: 'title'
    },
    {
      title: '图标',
      dataKey: 'icon',
      width: 100,
      bodyCellRender: (column, record, index) => {
        return (
          <Icon icon={record.icon} />
        )
      },
    },
    {
      title: '路径',
      dataKey: 'menuPath'
    },
    {
      title: '编号',
      dataKey: '_id',
      width: 250,
      bodyCellRender: (column, record, index) => {
        return (
          <Typography.Text copyable>
            {record._id}
          </Typography.Text>
        )
      },
    },
    {
      title: '创建时间',
      dataKey: 'createdTime',
      width: 200,
    },
    {
      title: '更新时间',
      dataKey: 'updateTime',
      width: 200,
    },
    {
      title: '操作',
      width: 200,
      dataKey: 'operation',
      bodyCellRender: (_columns, record) => {
        return (
          <div className='flex gap10'>
            <Button
              type='primary'
              onClick={() => {
                setTitle('编辑')
                setRadioValue(record.parentId === '0' ? 'one' : 'two')
                modalRef.current?.open()
                setTimeout(() => {
                  form.setFieldsValue(record)
                }, 0)
              }}
            >编辑</Button>
            <Button
              status='error'
              onClick={() => {
                setTitle('删除')
                deleteItem(record)
              }}
            >删除</Button>
          </div>
        )
      }
    },
  ]

  const deleteItem = async (record: any) => {
    try {
      await deleteMenuApi([record._id])
      Message.success('删除成功');
      actionRef.current?.refresh()
    } catch (error) {

    }
  }

  const onOK = async () => {
    try {
      const requestData = form.getFields()
      if (requestData._id) {
        await updateMenuApi(
          requestData._id,
          omit(requestData, omitFields)
        );
      } else {
        await addMenuApi({
          ...requestData,
          ...getValueIfQualified({
            menuPath: '/',
            parentId: '0',
          }, radioValue === 'one')
        });
      }
      modalRef.current?.close()
      actionRef.current?.refresh()
    } catch (error) {
    }
  }

  return (
    <Page className={styles.MenusList}>
      <div className='h-5'></div>
      <Table
        search={{
          columns: [
            {
              formItem: {
                name: 'title',
                label: '标题'
              },
              type: 'text'
            },
          ]
        }}
        oprationContent={(
          <Card borders={[]}>
            <div>
              <Button
                type='primary'
                icon={<Icon icon="add" />}
                onClick={() => {
                  setTitle('添加')
                  setRadioValue('one')
                  modalRef.current?.open()
                }}
              >
                添加
              </Button>
            </div>
          </Card>
        )}
        actionRef={actionRef}
        borderWidth={0}
        columns={columns}
        data={async (pagination, search) => {
          let list: any[] = []
          try {
            const res: any = await getMenuPaginationApi({
              ...pagination,
              ...search
            });
            list = res.data
            return {
              list,
              total: res.total,
            }
          } catch (error) {
          }

        }}
        pagination={{
          sort: ['page']
        }}
      />
      <Modal title={title} onOK={onOK} ref={modalRef}>
        {title === '添加' && (
          <>
            <Radio.Group
              value={radioValue}
              onCheckedChange={(value) => {
                setRadioValue(value as any)
              }}
              options={[
                {
                  label: '一级菜单',
                  value: 'one',
                },
                {
                  label: '二级菜单',
                  value: 'two',
                },
              ]}
            />
            <div className='h-5'></div>
          </>
        )}


        <Form
          form={form}
          layout='vertical'
        >
          {radioValue === 'one' && (
            <Form.Item label="图标" name='icon'>
              <InputText />
            </Form.Item>
          )}
          <Form.Item label="标题" name='title'>
            <InputText />
          </Form.Item>

          {radioValue === 'two' && (
            <>
              <Form.Item label="路径" name='menuPath'>
                <InputText />
              </Form.Item>
              <Form.Item label="父级Id" name='parentId'>
                <InputText />
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>
    </Page>
  )
}
export default MenusList